import React, { Component } from "react"
import { Provider, connect } from "react-redux"
import { bindActionCreators } from "redux"
import { createStore, applyMiddleware } from "redux"
import createSagaMiddleware from "redux-saga"
import rootReducer from "@/redux/rootReducer"
import rootSaga from "@/redux/rootSaga"

import * as actions from "@/redux/module-list/action"

const sagaMiddleware = createSagaMiddleware()
const store = createStore(rootReducer, applyMiddleware(sagaMiddleware))
sagaMiddleware.run(rootSaga)

class ListWithSaga extends Component {
    render() {
        return (
            <Provider store={store}>
                <List />
            </Provider>
        )
    }
}

class List extends Component {
    componentDidMount() {
        console.log("redux-saga props", this.props)
    }

    render() {
        const { list, getListRedux } = this.props
        return (
            <div>
                <p>with redux-saga</p>
                <button onClick={getListRedux}>get list</button>

                <hr />
                <ol>
                    {list.map(v => (
                        <li key={v.id}>
                            <p>{v.title}</p>
                        </li>
                    ))}
                </ol>
            </div>
        )
    }
}

// 将模块的state注入到组件中
function mapStateToProps(state) {
    return { ...state.ModuleList }
}

// 将模块的action注入到组件中
function mapActionsToProps(dispatch) {
    return bindActionCreators(actions, dispatch)
}

List = connect(
    mapStateToProps,
    mapActionsToProps
)(List)

export default ListWithSaga
